<?php
class mensuales extends Controller {

	var $maxval;
	
	function mensuales(){
		parent::Controller();
		$this->load->helper('text');
		$this->load->library("rapyd");
	}

	function index() {
		$this->rapyd->load("datagrid2");
		$this->rapyd->load("dataform");
		$this->load->helper('openflash');
		      
		$script ='
		$(function() {
			$(".inputnum").numeric(".");
		});
		';      
		                            
		if($this->uri->segment(4)) $anio=$this->uri->segment(4); elseif(isset($_POST['anio'])) $anio=$_POST['anio'];
		if (empty($anio))$anio=date("Y");

		$fechai=$anio.'0101';
		$fechaf=$anio.'1231';
		
		$filter = new DataForm('estadisticas/mensuales');
		$filter->title('Filtro de B&uacute;squeda');
		$filter->script($script, "create");
		$filter->script($script, "modify");		
		
		$filter->anio = new inputField("A&ntilde;o", "anio");
		$filter->anio->size=4;
		$filter->anio->insertValue=$anio;
		$filter->anio->maxlength=4;
		$filter->anio->rule = "trim";
		$filter->anio->css_class='inputnum'; 
		
		//$filter->anio->onkeypress="return acceptNum(event)";
		
		$filter->button("btnsubmit", "Buscar", form2uri(site_url('estadisticas/mensuales/index'),array('anio')), $position="BL");
		$filter->build_form();
		
		$data=$this->_sincrodata($fechai,$fechaf);
		
		$grid = new DataGrid2('',$data);
        
		$grid->totalizar('total','cobrado','resta','numfac');
        
		$grid->column("Mes"        ,"mmes");
		$grid->column("Total"      , "<number_format><#total#>|2|,|.</number_format>"  ,'align=right');
		$grid->column("Cobrado"    , "<number_format><#cobrado#>|2|,|.</number_format>",'align=right');
        $grid->column("Resta"      , "<number_format><#resta#>|2|,|.</number_format>",'align=right');
		$grid->column("Cant. Letras" , "numfac"   ,'align=right');
		$grid->build();
		
		$data['content'] =  open_flash_chart_object(680,300, site_url("estadisticas/mensuales/grafico/$anio"));
		$data['content'] .= $filter->output.$grid->output;
		$data['title'] = "<h1>Ventas y Cobros</h1>";
		$data["head"]    = script("jquery.pack.js").script("plugins/jquery.numeric.pack.js").script("plugins/jquery.floatnumber.js").$this->rapyd->get_head();
		$this->load->view('view_ventanas', $data);
	}
	
	function grafico($anio=NULL){
        
        //si no trae u parametro devuelve la consulta
        
		if (empty($anio)) return;
         
		//llama a las librerias
        $this->load->library('Graph');
        $this->load->library('calendar');
        
		$titulo=$data_1=$data_2=$data_tips_1=$data_tips_2=array();
		
        $fechai=$anio.'0101';
		$fechaf=$anio.'1231';
		
		//se trae la consulta
        
        $data=$this->_sincrodata($fechai,$fechaf);
                
		$om=1; while($this->maxval/$om>100) $om=$om*10;
		 
        //muestra registro de consultas
        
		foreach($data AS $row){
			
            $nmes[]  =$this->lang->line('cal_'.strtolower($row['mes']));
            
            $titulo[]=$row['mes'];
            $mes[]=$row['numes'];
			$data_1[]=$row['total'];
			$data_2[]=$row['cobrado'];
            
			$data_tips_1[]=graph::esc(number_format($row['total'],2,',','.'));
			$data_tips_2[]=graph::esc(number_format($row['cobrado'],2,',','.'));
            			
		}
		
		
        //crea las barras
        
        $odata_1 = new bar( 50, '#7500AB' );
		$odata_1->key( 'Venta', 10 );
		$odata_1->data = $data_1;
		$odata_1->tips = $data_tips_1;
        
		
		$odata_2 = new bar( 50, '0x80a033' );
		$odata_2->key( 'Cobranza', 10 );
		$odata_2->data = $data_2;
		$odata_2->tips = $data_tips_2;
       	
		
        //crea los link para ir al siguiente grafico
        
        for($i=0;$i<count($data_1);$i++ ){
			$mes=$i+1;      			
			$odata_1->links[]= site_url("/estadisticas/diarias/index/$mes/$anio");
			$odata_2->links[]= site_url("/estadisticas/diarias/index/$mes/$anio");
				 	                                                                                  
		}
        
        //gener el grafico
                
        $g = new Graph();
		if($this->maxval>0){
			$g->title( 'Ventas y Cobranzas del '.$anio,'{font-size:18px; color:#0D358A}');
			$g->set_is_decimal_separator_comma(1);
			         
			$g->data_sets[] = $odata_1;
			$g->data_sets[] = $odata_2;
			
			$g->set_y_max(ceil($this->maxval));
			$g->y_label_steps( 5 );
			$g->set_x_labels($nmes);
			
            $ejey=number_format($om,0,'','.');
			//$g->set_y_legend( 'Venta X '.$ejey.' (Bs)',14,'#0D358A' );
			$g->set_x_legend( 'Mes', 14,'0x639F45' );
			$g->set_tool_tip( '#key#<br>Mes: #x_label# <br>Monto: #tip#' );
		}else
			$g->title( 'No existen ventas en la Fecha Seleccionada','{font-size:18px; color: #d01f3c}');
            $g->bg_colour='#FFFFFF';
            //$g->set_bg_image(site_url('/images/ventafon.png'), 'center', 'middle' );
            echo utf8_encode($g->render());
	}
	function _sincrodata($fechai,$fechaf){
		$maxval=0;
		
		$mSQL_1="SELECT fecha,MONTHNAME(fecha)AS mes,MONTH(fecha) numes,
        DATE_FORMAT(fecha,'%m/%Y')AS mmes,
        sum(monto) total,SUM(abono) cobrado,sum(monto)-SUM(abono) resta,  
		COUNT(*) AS numfac FROM itpagos WHERE fecha>='$fechai' AND fecha<='$fechaf' GROUP BY MONTH(fecha)";

		//echo $mSQL_1;
        
        $DB2 = $this->load->database('default', TRUE); 
		
		$query_1=$this->db->query($mSQL_1);
		$row = $query_1->row();

		$i_1=0;
		$data=$comodin=array();
		$cant_1=$query_1->num_rows();
	
		if ($cant_1> 0){
			
            $row_1 = $query_1->first_row('array');
            while($i_1<$cant_1){
                $comodin['mes']     =$row_1['mes'];
                $comodin['numes']   =$row_1['numes'];
                $comodin['mmes']    =$row_1['mmes'];
                $comodin['total']   =$row_1['total'];
                $comodin['cobrado'] =$row_1['cobrado'];
                $comodin['resta']   =$row_1['resta'];
                $comodin['numfac']  =$row_1['numfac'];
               
                $row_1 = $query_1->next_row('array');
            
            
				if ($comodin['total']   > $maxval) $maxval=$comodin['total'];
				if ($comodin['cobrado'] > $maxval) $maxval=$comodin['cobrado'];
				if ($comodin['resta']   > $maxval) $maxval=$comodin['resta'];
                
                $data[]=$comodin;
				if(count($data)>=13) break;
                $i_1++;
            }
            		
		}
    
        
		$this->maxval=$maxval;
		return($data);
	}
}
?>
